var BILDR_VERSION = 32;

function initBase(){ 
	
	viewScope.baseButtons = null;
	baseButtons = [];

	//Check for Buttons in Page Custom Properties
	if (typeof compositeData != "undefined") {
		if (compositeData.buttonTitles != null){
			for(var x=0;x<compositeData.buttonTitles.length;x++){
				newButton(compositeData.buttonTitles[x],compositeData.buttonTitles[x])
			}
		}
	}

	//Application Settings
	if(applicationScope.initConfig === null){
				
		applicationScope.put( "themeImages", "/.ibmxspres/domino/oneuiv2/images/");
		
		/***************************************************************
		Layout is setup in layout.properties (in Resources/Files)
		Can also be setup programmatically (do so in this function for max caching):
		
		Top Tab:				newTopTab("Link","Title")
		Main Tab:				newTab("Link","Title")
		Side Bar Menu Item:		newSideMenu("Link","Title")
		Footer Columns:			var col=new newFooterColumn("Column Title","StyleClass")	
		Footer Column Items:	col.addLink("Link","Title")
		Buttons:				newGlobalButton("Link","Title")
		***************************************************************/
			
		// Create Layout from Properties File
		var createProperties = createFromProperties();
		
		//Check no errors in Property File
		if(createProperties != ""){
			print ("Error In Layout Property File: " + database.getFilePath()+ " : " + createProperties);
		}else{
			//Mark cache initialized		
			applicationScope.initConfig = true;
		}	
	}
	
	//Session Settings
	var currentUser = @UserName();
	
	//Workaround here to re-init the session vars if another user has logged in
	if ( !sessionScope.initConfig || !sessionScope.get("userName").equalsIgnoreCase(currentUser) ) {
		
		sessionScope.put("userName", currentUser);
			
		var con = facesContext.getExternalContext();
		var request = con.getRequest();
		var server = request.getServerName();
		var protocolFull = request.getProtocol();
		var protocolOnly = protocolFull.split("/")[0]; 
		var port = (request.getServerPort().equals(80)) ? "" : ":" + request.getServerPort();
		sessionScope.put("path", con.getRequestContextPath());
		//Path (including full server name)
		sessionScope.put("pathFull", protocolOnly.toLowerCase() + "://" + server + port + con.getRequestContextPath());	
		sessionScope.put("isSessionAuth", @Contains(facesContext.getExternalContext().getRequest().getHeader("Cookie"), "DomAuthSessId") === 1 ? true : false); //dnt
		//Is Client? - Get session id
		if(@ClientType() == "Notes"){
			sessionScope.sessionID = facesContext.getExternalContext().getRequest().getSession().getId();
		}	
		
		var roles = context.getUser().getRoles();
		sessionScope.put("userRoles", roles);
		sessionScope.put("isDebug", roles.contains("[debug]"));
		
		//retrieve preferences
		var db = sessionAsSigner.getDatabase(database.getServer(), database.getFilePath());		//open as signer
		var viewPrefs:NotesView = db.getView("$v-preferences");
		var docPrefs:NotesDocument = viewPrefs.getFirstDocument();
		
		if (docPrefs == null) {
			
			if (view.getPageName().indexOf("settings.xsp") == -1) {		//only preferences can be opened without config
	
				sendError("Bildr has not been set up correctly: no configuration document found. <p>You can:" +
					"<ul><li>Contact the application administrator, or" +
					"<li>If you are the application administrator click <a href=\"settings.xsp\">here</a></li></ul></p>");
			
			}
			
			return;
		
		} else if (docPrefs.getItemValueInteger("Tx_version") < BILDR_VERSION ){
			
			if (view.getPageName().indexOf("settings.xsp") == -1) {		//only preferences can be opened without config
			
				sendError("Bildr has not been set up correctly: the application administrator needs to update the configuration document.<p>You can:" +
					"<ul><li>Contact the application administrator, or" +
					"<li>If you are the application administrator click <a href=\"settings.xsp\">here</a></li></ul></p>");
			}
			return;
			
		}
		
		//Clear sessionscope variables related to upload
		var iter:java.util.Iterator = sessionScope.keySet().iterator();
		while (iter.hasNext()) {
			var key = iter.next();
			if (key.toString().indexOf("upload") == 0) {	
				sessionScope.remove(key);
			}
		}
					
		sessionScope.put("titlebarTitle", docPrefs.getItemValueString("Tx_DBTitle"));
		sessionScope.put("titlebarSubtitle", docPrefs.getItemValueString("Tx_DBSubtitle"));
		sessionScope.put("contactInfo", docPrefs.getItemValue("Tx_DBWebMail"));
		sessionScope.put("numPicsView", docPrefs.getItemValueInteger("Nb_DBWebPicsPerPage"));
		sessionScope.put("numPicsLatest", docPrefs.getItemValueInteger("Nb_DBWebPicsLatest"));
		sessionScope.put("numPicsGallery", docPrefs.getItemValueInteger("Nb_DBWebPicsGallery"));
		sessionScope.put("numCommentsHomepage", docPrefs.getItemValueInteger("Nb_DBWebPicsComments"));
		sessionScope.put("numComments", docPrefs.getItemValueInteger("Nb_DBCommentsPerPage"));
		sessionScope.put("allowComments", (docPrefs.getItemValueString("Tx_AllowComments").equalsIgnoreCase("Yes")));
		sessionScope.put("imageExtensions", docPrefs.getItemValue("Tx_ImageExtensions") );		//array of valid image extensions
		sessionScope.put("imageExtensionsDesc", docPrefs.getItemValueString("Tx_ImageExtensionsDescription") );	
		sessionScope.put("uploadRuntimes", docPrefs.getItemValue("Tx_Runtimes").join(",") );
		sessionScope.put("uploadMaxSize", docPrefs.getItemValueInteger("Nb_MaxImageSize") );
		sessionScope.put("theme", docPrefs.getItemValueString("Tx_Theme") );
		
		sessionScope.put("tabTags", docPrefs.getItemValueString("Tx_PrefShowTags") );
		sessionScope.put("GoogleServerKey", docPrefs.getItemValueString("Tx_DBGoogleKey") );
		
		sessionScope.put("showFooter", (docPrefs.getItemValueString("Tx_LayoutShowFooter").equalsIgnoreCase("Yes") ) );
		sessionScope.put("showGeoLocation", (docPrefs.getItemValueString("Tx_DBUseLocation").equalsIgnoreCase("Yes")) );
		
		//Resize configuration
		sessionScope.put("resizeConfig-Smaller", {
			mode : getResizeDimension(docPrefs, "imp_resizemode_sm"),
			x : getResizeDimension( docPrefs, "imp_sm_x_res"),
			y : getResizeDimension( docPrefs, "imp_sm_y_res"),
			maxValue : getResizeDimension( docPrefs, "imp_maxvalue_sm"),
			perc : getResizeDimension( docPrefs, "imp_percentvalue_sm")
		});
		sessionScope.put("resizeConfig-Thumbnail", {
			mode : getResizeDimension(docPrefs, "imp_resizemode_tn"),
			x : getResizeDimension( docPrefs, "imp_tn_x_res"),
			y : getResizeDimension( docPrefs, "imp_tn_y_res"),
			maxValue : getResizeDimension( docPrefs, "imp_maxvalue_tn"),
			perc : getResizeDimension( docPrefs, "imp_percentvalue_tn")
		});
		
		sessionScope.put("initConfig", true);
	}
}

function sendError(message) {
	sessionScope.put("errorMessage", message);
	context.redirectToPage("error");
}

function getResizeDimension(doc:NotesDocument, field:String) {
	var result = 0;
	
	var item:NotesItem = doc.getFirstItem(field);
	if (item == null) { return 0;
	}

	var itemVal = item.getValues();
	if (itemVal==null) { return 0;
	} 
	
	itemVal = itemVal.elementAt(0);
	
	switch(item.getType() ){
		case 1280:
			if (itemVal.toString() != "") {
				result = @Integer(itemVal.toString());
			}
			break;
			
		case 768:
			result =  @Integer(itemVal);
			break; 
	}
	return result;
}

/*
 * Returns the URL to the profile photo of a specific author
 * Results are cached in the sessionScope
 */
function getProfilePhoto(author) {
	var key = "profilePhotoCache";	
	if (!sessionScope.containsKey(key)) {
		//Create hashmap to store profile pictures
		sessionScope.put(key, new java.util.HashMap() );
	}	
	var profilePhotoLinks = sessionScope.get(key);
	if (profilePhotoLinks.get(author) == null) {
		var locView:NotesView = session.getDatabase("", database.getFilePath()).getView("lkp_Photos");
		var locDoc:NotesDocument = locView.getDocumentByKey(author, true);
		var url = "";
		if (locDoc != null){
			url = "/0/" + locDoc.getUniversalID() + "/$File/64x64_photo.jpg";
		}
		else {
			url = "/profileNoPhoto.png";
		}
		profilePhotoLinks.put(author, url);
		sessionScope.put("profilePhotoCache", profilePhotoLinks);
	}
	return sessionScope.get("pathFull") + profilePhotoLinks.get(author);
}

Bildr = {

	deletePicture : function(picNoteId) {

		try {
			var docPic = database.getDocumentByID( picNoteId );
			var picId = docPic.getItemValueString("Tx_id");
					
			//remove picture id from albums
			
			//open current db as signer
			var db:NotesDatabase = sessionAsSigner.getDatabase( database.getServer(), database.getFilePath() );
			var dcAlbums:NotesDocumentCollection = db.search( "Form=\"$f-album\" & @IsMember(\"" + picId + "\"; Tx_pictureIds)" );
			
			var docAlbum:NotesDocument = dcAlbums.getFirstDocument();
	
			while (docAlbum != null) {
				
				var picIds = @Trim(@Replace(docAlbum.getItemValue("Tx_pictureIds"), picId, ""));
				docAlbum.replaceItemValue("Tx_pictureIds", picIds);
				docAlbum.save();
				
				docAlbum = dcAlbums.getNextDocument(docAlbum);
			}		
	
			//delete picture document
			docPic.removePermanently(true);
		}catch(e) {
			print("Bildr.deletePicture: " + e.toString() );
		}
	}	
	
}
